<template>
  <div>
    <Header :title="'返回'" :subTitle="'售后单列表'" :hasBackPath="true" @headerBack="headerBack"></Header>
    <a-card :bordered="false">
      <div class="font_title">创建售后单</div>
      <a-descriptions :column="3" title=" 售后单信息">
        <a-descriptions-item label="售后单号"> {{ orderDetail.refundSn }}</a-descriptions-item>
        <a-descriptions-item label="订单编号">
          <router-link :to="`/box/salesOrder/detail/${orderDetail.orderId}`">{{ orderDetail.orderSn }}</router-link>
        </a-descriptions-item>
        <a-descriptions-item label="创建时间"> {{ orderDetail.createTime }}</a-descriptions-item>
        <a-descriptions-item label="支付流水号"> {{ orderDetail.tradeNo ? orderDetail.tradeNo : '-' }}</a-descriptions-item>
        <a-descriptions-item label="支付方式"> {{ orderDetail.paymentType }}</a-descriptions-item>
        <a-descriptions-item label="支付时间"> {{ orderDetail.createDate }}</a-descriptions-item>
        <a-descriptions-item label="订单类型">{{ typeType[orderDetail.type] }}</a-descriptions-item>
      </a-descriptions>
      <a-divider style="margin-bottom: 16px" dashed />
      <detail-list title=" 会员信息">
        <detail-list-item term="昵称">{{ orderDetail.nickName }}</detail-list-item>
        <detail-list-item term="手机号">{{ orderDetail.phone }}</detail-list-item>
        <detail-list-item term="归属搭配师">{{ orderDetail.name }}</detail-list-item>
      </detail-list>
      <a-divider style="margin-bottom: 32px" />
      <div class="title">售后原因</div>
      <a-form-model ref="rulesForm" :label-col="{ span: 2 }" :wrapper-col="{ span: 18 }" :model="form" :rules="rules">
        <a-form-model-item label="售后原因" prop="region">
          <a-select v-model="form.region" @change="changeType">
            <a-select-option value="">请选择</a-select-option>
            <a-select-option v-for="(item, index) in refundReasonList" :key="index" :value="item.code">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="退款说明">
          <a-input v-model="form.desc" type="textarea" />
        </a-form-model-item>
        <a-form-model-item label="凭证图片">
          <JImageUpload :uploadParams="getUploadParams()" :isMultiple="true" :number="5" @fileChange="fileChange" v-model="fileList"></JImageUpload>
          <div>注：不超过5张</div>
        </a-form-model-item>
        <div v-if="form.region">
          <a-divider style="margin-bottom: 32px" />
          <div class="title">售后商品</div>
          <a-table ref="table" size="default" style="margin-bottom: 24px" :rowSelection="rowSelection" :rowKey="record => record.id" :columns="goodsColumns" :dataSource="dataSourceList">
            <span slot="serial" slot-scope="text, record, index">
              {{ index + 1 }}
            </span>
            <span slot="goods" slot-scope="text, record">
              <ListInfo :record="record"></ListInfo>
            </span>
            <span slot="productQuantity" slot-scope="text, record, index">
              <a-input-number v-model="record.productQuantity" :max="record.orderNumber" :min="1" @change="onChange(record, index)" />
            </span>

            <span slot="orderDetailRefundAmount" slot-scope="text, record, index">
              <a-input-number v-model="record.orderDetailRefundAmount" :max="record.refundNumber" />
              <a v-if="form.region != 6" style="margin-left: 10px" @click="calculation(record, index)">自动计算</a>
            </span>
          </a-table>

          <div class="price">
            <div></div>
            <div>
              <p>售后商品：{{ commodity }}件</p>
              <p>实付金额：{{ payNumber }}元</p>
              <p>退款金额：{{ retreatNumber }}元</p>
            </div>
          </div>
          <div v-if="form.region != 6">
            <a-divider style="margin-bottom: 32px" />
            <div>
              <span class="title">取件地址</span>
              <a style="margin-left: 50px" @click="changeAdds">修改</a>
            </div>
            <a-form-model-item label="收货人" style="margin-top: 24px; margin-bottom: 12px"> {{ logistic.name }} </a-form-model-item>
            <a-form-model-item label="手机号" style="margin-bottom: 12px"> {{ logistic.phone }} </a-form-model-item>
            <a-form-model-item label="详细地址">{{ logistic.province }} {{ logistic.city }} {{ logistic.district }} {{ logistic.address }}</a-form-model-item>
            <a-form-model-item label="预约快递" prop="express">
              <a-select v-model="form.express">
                <a-select-option value="0"> 否 </a-select-option>
                <a-select-option value="1"> 是</a-select-option>
              </a-select>
            </a-form-model-item>

            <a-form-model-item label="快递单号" prop="trackingNumber" v-if="form.express == 0">
              <a-input placeholder="请输入快递单号" v-model="form.trackingNumber" />
            </a-form-model-item>
            <a-form-model-item label="取件时间" prop="time" v-else>
              <j-date placeholder="请选择结束时间" v-model="form.time" :show-time="true" date-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
            </a-form-model-item>
          </div>
        </div>
      </a-form-model>
      <div style="margin-top: 40px">
        <a-button @click="submitForm" type="primary" style="margin-right: 10px" :loading="loading">提 交</a-button>
        <a-button @click="cancelClick">取 消</a-button>
      </div>
    </a-card>

    <Address ref="address" :unionId="orderDetail.unionid" :defLogistic="logistic" @newAddress="newAddress" :title="'选择地址'"></Address>
    <LogisticsDetail ref="logistics"></LogisticsDetail>
  </div>
</template>
<script>
import Header from '@/views/box/components/layouts/Header'
import DetailList from '@/components/tools/DetailList'
import JImageUpload from '@/components/qiniuUpload/JImageUpload.vue'
import globalData from '@/assets/js/common'
import ListInfo from '@views/box/components/goodsInfo/listInfo'
import { STable, Ellipsis } from '../components'
import Address from '@/views/box/components/Address/AddressList'
import JournalTable from './components/journalTable.vue'
import LogisticsDetail from './components/logisticsDetail.vue'
import JDate from '@/components/jeecg/JDate'
import { orderInfo, save, refundReason } from '@/api/box/sales'
const DetailListItem = DetailList.Item
const goodsColumns = [
  {
    title: '序号',
    dataIndex: 'serial',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '商品',
    dataIndex: 'barcode',
    scopedSlots: { customRender: 'goods' },
    width: '400px'
  },
  {
    title: '款号',
    dataIndex: 'productCode'
  },
  {
    title: '原价',
    dataIndex: 'productPrice',
    align: 'center'
  },
  {
    title: '活动减免',
    dataIndex: 'productFavorablePrice',
    align: 'center'
  },
  {
    title: '会员折扣',
    dataIndex: 'vipPrice',
    align: 'center'
  },
  {
    title: '售后数量',
    dataIndex: 'productQuantity',
    align: 'center',
    scopedSlots: { customRender: 'productQuantity' }
  },
  {
    title: '订单数量',
    dataIndex: 'orderNumber',
    align: 'center'
  },
  {
    title: '实付金额',
    dataIndex: 'priceactual',
    align: 'center'
  },
  {
    title: '退款金额',
    dataIndex: ' orderDetailRefundAmount',
    align: 'center',
    scopedSlots: { customRender: 'orderDetailRefundAmount' }
  }
]
export default {
  components: {
    Header,
    DetailList,
    DetailListItem,
    JImageUpload,
    ListInfo,
    STable,
    Ellipsis,
    Address,
    JournalTable,
    LogisticsDetail,
    JDate
  },
  data() {
    this.goodsColumns = goodsColumns
    return {
      visible: false,
      loading: false,
      id: '',
      typeType: {
        10: 'BOX',
        20: '导购',
        30: '有搭',
        40: '主题盒子'
      },
      conditionType: {
        0: '不影响二次销售,7天无理由退货',
        1: '尺码偏大/小',
        2: '商品与描述不符',
        3: '价格问题',
        4: '质量问题',
        5: '商品缺货',
        6: '买贵退差价'
      },
      tableData: [], // 操作日志
      dataSourceList: [],
      refundReasonList: [], // 售后原因列表
      type: 1,
      form: {
        region: '', // 售后原因
        desc: '', // 退款说明
        time: '', // 取件时间
        trackingNumber: '' // 物流单号
      },
      fileList: [],
      newLifePhotos: [], // 凭证图片
      selectedRowKeys: [], // 选中的id
      selectedRows: [], // 选中的条数据
      oddNumbers: '', // 物流单号
      remarkValue: '', // 添加备注
      pieceTime: '', // 取件时间
      modalType: '', // 弹框类型
      modalText: '', // 弹框title
      rules: {
        region: [{ required: true, message: '请选择售后原因', trigger: 'change' }],
        express: [{ required: true, message: '请预约快递', trigger: 'change' }],
        trackingNumber: [{ required: true, message: '请填写快递单号', trigger: 'change' }],
        time: [{ required: true, message: '请选择取件时间', trigger: 'change' }]
      },
      orderDetail: {},
      logistic: {
        phone: '',
        name: '',
        province: '',
        city: '',
        district: '',
        address: ''
      },
      trackingNumber: '', // 物流单号
      orderId: '' // 订单主id
    }
  },
  beforeRouteLeave(to, from, next) {
    this.$destroy()
    next()
  },
  computed: {
    onChangeEntryTime(date, dateString) {
      this.form.time = dateString
    },
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    },
    // 实付金额
    payNumber() {
      let total = 0
      this.selectedRows.forEach(item => {
        total += Math.round(Number(item.productQuantity) * Number(item.priceactual) * 100) / 100
      })
      return Math.round(total * 100) / 100
    },
    // 退款金额
    retreatNumber() {
      let total = 0
      this.selectedRows.forEach(item => {
        total = Math.round(total * 100) / 100 + Math.round(Number(item.orderDetailRefundAmount) * 100) / 100
      })
      return Math.round(total * 100) / 100
    },
    // 售后商品数量
    commodity() {
      let total = this.selectedRows.reduce((total, obj) => {
        return (total += Number(obj.productQuantity))
      }, 0)
      return total
    }
  },
  created() {
    this.orderSn = this.$route.params.id
    this.orderInfo() // 售后单详情
    this.refundReason() // 售后原因列表
  },
  methods: {
    changeType() {
      if (this.form.region == 6) {
        this.dataSourceList.forEach(item => {
          item.orderDetailRefundAmount = ''
        })
      } else {
        this.dataSourceList.forEach(item => {
          item.orderDetailRefundAmount = item.orderDetail
        })
      }
    },
    onChange(record, index) {
      this.dataSourceList[index].orderDetailRefundAmount = Math.round(record.priceactual * record.productQuantity * 100) / 100 // 退款金额
      this.dataSourceList[index].refundNumber = Math.round(record.priceactual * record.productQuantity * 100) / 100 // 退款金额最大输入的值
    },
    calculation(record, index) {
      this.dataSourceList[index].orderDetailRefundAmount = Math.round(record.priceactual * record.productQuantity * 100) / 100
      this.dataSourceList[index].refundNumber = Math.round(record.priceactual * record.productQuantity * 100) / 100 // 退款金额最大输入的值
    },
    refundReason() {
      refundReason().then(res => {
        if (res.code == 0) {
          this.refundReasonList = res.data
        }
      })
    },
    orderInfo() {
      let requestData = {
        orderSn: this.orderSn
      }
      let params = {
        page: {
          pageNo: 1,
          pageSize: 10
        },
        requestData: requestData
      }
      orderInfo(params).then(res => {
        if (res.code === 0) {
          this.orderDetail = res.data.order
          this.logistic = res.data.logistics
          this.logistic.id = res.data.logistics.customerLogisticsId
          this.form.desc = this.orderDetail.refundRemark
          this.dataSourceList = res.data.orderDetail

          this.dataSourceList.forEach(item => {
            item.priceactual = Number(item.priceactual)
            item.productQuantity = Number(item.productQuantity)
            item.orderNumber = JSON.parse(JSON.stringify(item.productQuantity))
            item.refundNumber = JSON.parse(JSON.stringify(Number(item.priceactual) * Number(item.productQuantity)))
            item.orderDetailRefundAmount = Math.round(item.priceactual * item.productQuantity * 100) / 100
            item.orderDetail = JSON.parse(JSON.stringify(item.orderDetailRefundAmount)) // 非买贵退差价 退款金额不展示默认值
          })
          this.orderId = res.data.order.orderId // 订单主ID
          this.unionid = res.data.order.unionid
        }
      })
    },

    // 修改取件地址
    changeAdds() {
      this.$refs.address.show()
    },
    newAddress(record) {
      this.logistic = record
      this.logistic.name = record.contactName
      this.logistic.phone = record.contactPhone
      this.logistic.customerLogisticsId = record.id
      this.$emit('changeAddress', record)
    },
    // 售后商品多选框
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    headerBack() {
      this.$router.back()
    },
    // 上传图片
    fileChange(list) {
      this.newLifePhotos = list
    },
    // 上传图片
    getUploadParams() {
      return { ...globalData.uploadParams }
    },
    // 确定
    submitForm() {
      this.$refs.rulesForm.validate(valid => {
        if (valid) {
          if (this.selectedRows.length <= 0) {
            this.$message.warning('请选择售后商品')
            return
          } else {
            for (let i = 0; i < this.selectedRows.length; i++) {
              if (this.selectedRows[i].priceactual != 0 && !this.selectedRows[i].orderDetailRefundAmount) {
                this.$message.warning('请填写退款金额')
                return false
              }
            }
          }
          let logistics = {
            address: this.logistic.address,
            city: this.logistic.city,
            customerLogisticsId: this.logistic.id,
            district: this.logistic.district,
            name: this.logistic.name,
            phone: this.logistic.phone,
            province: this.logistic.province
          }
          let orderDetail = this.selectedRows.map(item => {
            const newItem = {
              sku: item.sku,
              orderId: item.orderId,
              id: item.id,
              refundQty: item.productQuantity,
              orderDetailRefundAmount: item.orderDetailRefundAmount
            }
            return newItem
          })
          let productImageIds = []
          if (this.newLifePhotos) {
            this.newLifePhotos = this.newLifePhotos.map(e => e.url)
            productImageIds = this.newLifePhotos.map(item => {
              return { sourceProductImagePath: item }
            })
          }
          let requestData = {
            refundAmount: 0, // 退款类型
            refundRemark: this.conditionType[this.form.region], // 售后原因
            amount: this.retreatNumber.toString(), // 金额
            orderId: this.orderId, // 订单主id
            memo: this.form.desc, // 退款说明
            getDate: this.form.time, // 取件时间
            trackingNumber: this.form.trackingNumber, //物流单号
            orderDetail: orderDetail, // 售后商品
            productImageIds: productImageIds, // 凭证图片
            logistics: logistics, // 取件地址
            unionId: this.unionid, //
            isTracking: this.form.express == 1 ? false : true // 预约快递
          }
          let params = {
            page: {
              pageNo: 1,
              pageSize: 10
            },
            requestData: requestData
          }
          save(params).then(res => {
            this.loading = true
            if (res.code == 0) {
              this.$message.success('保存成功')
              this.$router.push(`/box/afterSalesOrder/list`)
            } else {
              this.fileList = []
              this.$message.warning(res.msg)
            }
          })
        } else {
          return false
        }
      })
    },
    // 取消
    cancelClick() {
      this.$router.push(`/box/afterSalesOrder/list`)
    },
    // 查看物流
    logistics() {
      this.$refs.logistics.show()
    }
  }
}
</script>
<style lang="less" scoped>
.title {
  color: rgba(0, 0, 0, 0.85);
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 16px;
}
.title_size {
  color: rgba(0, 0, 0, 0.85);
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 16px;
  margin-right: 50px;
}
.price {
  display: flex;
  justify-content: space-between;
}
.size_color {
  color: #40a9ff;
}
.single {
  margin-left: 100px;
  margin-right: 50px;
}
.address {
  margin-top: 20px;
  margin-bottom: 30px;
}
.font_title {
  color: rgba(0, 0, 0, 0.85);
  font-weight: 600;
  font-size: 24px;
  margin-bottom: 24px;
}
</style>

